//
//  GetURLFileLength.m
//  gdemm
//
//  Created by 李园园 on 16/12/7.
//  Copyright © 2016年 Goldencis. All rights reserved.
//

#import "GetURLFileLength.h"

@implementation GetURLFileLength
/**
 *  通过url获得网络的文件的大小 返回byte
 *
 *  @param url 网络url
 *
 *  @return 文件的大小 byte
 */
- (void)getUrlFileLength:(NSString *)url withResultBlock:(FileLength)block
{
    _block = block;
    NSMutableURLRequest *mURLRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    [mURLRequest setHTTPMethod:@"HEAD"];
    mURLRequest.timeoutInterval = 3.0;
    NSURLConnection *URLConnection = [NSURLConnection connectionWithRequest:mURLRequest delegate:self];
    [URLConnection start];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSDictionary *dict = [(NSHTTPURLResponse *)response allHeaderFields];
    NSNumber * size = [dict objectForKey:@"Content-Length"];
    [connection cancel];
    
    if (_block) {
         long long  len = size.longLongValue;
        long long length = len / 1024;
        if (length < 1) {
            _block([NSString stringWithFormat:@"%lld字节",len], nil);
        }
        if (length >= 1 && length < 1000) {
             _block([NSString stringWithFormat:@"%lldKB",length], nil);
        }
        length = length / 1024;
        if (length >= 1) {
            _block([NSString stringWithFormat:@"%lldMB",length], nil);
        }
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    if (_block) {
         _block(@"0KB", nil);
    }
    [connection cancel];
}@end
